package com.fitness.fitness.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fitness.fitness.convertor.UserConvertor;
import com.fitness.fitness.modal.coach.dto.CoachDto;
import com.fitness.fitness.modal.coach.vo.CoachVO;
import com.fitness.fitness.modal.member.vo.MemberVO;
import com.fitness.fitness.modal.response.ResponseEnum;
import com.fitness.fitness.modal.response.ServerResponseEntity;
import com.fitness.fitness.modal.user.dto.UserDto;
import com.fitness.fitness.modal.user.entity.Role;
import com.fitness.fitness.modal.user.entity.User;
import com.fitness.fitness.modal.user.param.UserPageQueryParams;
import com.fitness.fitness.modal.user.vo.UserVO;
import com.fitness.fitness.service.IMemberService;
import com.fitness.fitness.service.IRoleService;
import com.fitness.fitness.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/user")
public class UserController {

    @Resource
    private IMemberService memberService;

    @Resource
    private IUserService userService;

    @Resource
    private IRoleService roleService;

    @Resource
    private UserConvertor userConvertor;

    @SaCheckLogin
    @GetMapping("/me")
    public ServerResponseEntity<UserVO> me(HttpServletRequest request){
        String loginId = StpUtil.getLoginIdAsString();
        String[] uidAndUname = loginId.split("_");
        Long uid = Long.parseLong(uidAndUname[0]);
        UserVO userVO = new UserVO();
        User user = userService.getById(uid);
        userVO.setId(uid);
        userVO.setUsername(uidAndUname[1]);
        userVO.setNickname(user.getNickname());
        userVO.setAvatar(user.getAvatar());
        userVO.setMobile(user.getMobile());
//        Member member = memberService.getByUId(uid);
//
//        List<String> roles = roleService.getRoleList(uid);//StpUtil.getPermissionList(loginId);
//        memberVO.setRoles(roles);
        return ServerResponseEntity.success(userVO);
//        return ServerResponseEntity.fail(ResponseEnum.EXCEPTION);
    }

    /**
     * 分页获取
     */
    @GetMapping("/page")
    public ServerResponseEntity<IPage<UserVO>> page(UserPageQueryParams queryParams) {
        Page<UserVO> result = userService.getUserPage(queryParams);
        return ServerResponseEntity.success(result);
    }


    /**
     * 获取用户表单数据
     * @param userId
     * @return
     */
    @GetMapping("/getUserForm")
    public ServerResponseEntity<UserVO> getUserForm(@RequestParam Long userId) {
        User result = userService.getById(userId);
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        Role role = roleService.getRoleByUid(userId);
        UserVO userVO = userConvertor.entity2VO(result);
        userVO.setRoleId(role.getId());
        return ServerResponseEntity.success(userVO);
    }

    /**
     * 新增
     * @param userDto
     * @return
     */
    @PostMapping("/add")
    public ServerResponseEntity<Boolean> add(@RequestBody UserDto userDto) {
        ServerResponseEntity<Boolean> validate = validateUniq(userDto);
        if (validate != null) return validate;
        boolean result = userService.addUser(userDto);
        if(result){
            return ServerResponseEntity.success();
        }
        return ServerResponseEntity.fail("U10001","添加用户失败");
    }

    /**
     * 校验用户名/手机号是否唯一
     * @param userDto
     * @return
     */
    private ServerResponseEntity<Boolean> validateUniq(UserDto userDto) {
        String username = userDto.getUsername();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userService.getOne(userQueryWrapper);
        if(user != null) {
            return ServerResponseEntity.fail("U0001", "用户名已存在！");
        }
        String mobile = userDto.getMobile();
        userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("mobile", mobile);
        user = userService.getOne(userQueryWrapper);
        if(user != null) {
            return ServerResponseEntity.fail("u10001", "手机号已存在！");
        }
        return null;
    }

    /**
     * 修改
     * @param userDto
     * @return
     */
    @PutMapping("/update")
    public ServerResponseEntity<Boolean> update(@RequestBody UserDto userDto) {
        String username = userDto.getUsername();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userService.getOne(userQueryWrapper);
        if(user != null && !user.getId().equals(userDto.getId())) {
            return ServerResponseEntity.fail("U10001", "用户名已存在！");
        }
        String mobile = userDto.getMobile();
        userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("mobile", mobile);
        user = userService.getOne(userQueryWrapper);
        if(user != null && !user.getId().equals(userDto.getId())) {
            return ServerResponseEntity.fail("U10001", "手机号已存在！");
        }
        boolean result = userService.updateUserInfo(userDto);

        if(result) {
            return ServerResponseEntity.success();
        }
        return ServerResponseEntity.fail("U10002","更新用户信息失败");
    }

    /**
     * 删除
     * @param uid
     * @return
     */
    @DeleteMapping("/delete")
    public ServerResponseEntity<Boolean> delete(@RequestParam("uid") Long uid) {
        return userService.removeByUid(uid);
    }
}
